<template>
  <div ref="chartContainer" class="h-64 w-full"></div>
</template>

<script setup lang="ts">
  import { onMounted, ref, watch, onUnmounted } from 'vue'
  import { useTypingStore } from '@renderer/store/modules/typing.store'
  import * as echarts from 'echarts'

  const typingStore = useTypingStore()
  const chartContainer = ref<HTMLDivElement | null>(null)
  let chart: echarts.ECharts | null = null

  // 准备图表数据
  const getChartOptions = () => {
    const totalTime = typingStore.wpmHistory.length
    const labels: string[] = []
    const aggregatedWpm: number[] = []
    const aggregatedErrors: number[] = []

    if (totalTime <= 15) {
      // 时间≤15秒时显示每秒的数据点
      labels.push(...Array.from({ length: totalTime }, (_, i) => `${i + 1}s`))
      aggregatedWpm.push(...typingStore.wpmHistory)
      aggregatedErrors.push(...typingStore.errorHistory)
    } else {
      // 时间>15秒时每5秒聚合一次数据
      // 始终包含第一秒
      labels.push('1s')
      aggregatedWpm.push(typingStore.wpmHistory[0])
      aggregatedErrors.push(typingStore.errorHistory[0])

      // 按5秒间隔聚合数据
      for (let i = 5; i < totalTime; i += 5) {
        labels.push(`${i}s`)

        // 计算WPM：取这5秒的平均值
        const wpmSlice = typingStore.wpmHistory.slice(i - 5, i)
        const avgWpm = wpmSlice.reduce((sum, val) => sum + val, 0) / wpmSlice.length
        aggregatedWpm.push(Math.round(avgWpm))

        // 计算错误次数：取这5秒的总和
        const errorSlice = typingStore.errorHistory.slice(i - 5, i)
        const sumErrors = errorSlice.reduce((sum, val) => sum + val, 0)
        aggregatedErrors.push(sumErrors)
      }

      // 如果最后一秒不是5的倍数，添加最后一秒的数据
      if ((totalTime - 1) % 5 !== 0) {
        const lastSecond = totalTime - 1
        labels.push(`${lastSecond + 1}s`)

        // 获取最后一个5秒区间到结束的数据
        const lastIndex = Math.floor(lastSecond / 5) * 5

        // 计算WPM平均值
        const lastWpmSlice = typingStore.wpmHistory.slice(lastIndex, lastSecond + 1)
        const lastAvgWpm = lastWpmSlice.reduce((sum, val) => sum + val, 0) / lastWpmSlice.length
        aggregatedWpm.push(Math.round(lastAvgWpm))

        // 计算错误次数总和
        const lastErrorSlice = typingStore.errorHistory.slice(lastIndex, lastSecond + 1)
        const lastSumErrors = lastErrorSlice.reduce((sum, val) => sum + val, 0)
        aggregatedErrors.push(lastSumErrors)
      }
    }

    return {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        formatter: function (params) {
          let tooltip = params[0].axisValueLabel + '<br/>'
          params.forEach((param) => {
            tooltip += `${param.marker}${param.seriesName}: ${param.value}<br/>`
          })
          return tooltip
        }
      },
      legend: {
        data: ['WPM', '错误次数'],
        textStyle: {
          color: '#eee'
        }
      },
      grid: {
        left: '0%',
        right: '6%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: true, // 为柱状图留出边界间隙
          data: labels,
          axisLabel: {
            color: '#eee'
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(200, 200, 200, 0.3)'
            }
          },
          name: '时间(秒)',
          nameTextStyle: {
            color: '#eee'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: 'WPM',
          position: 'left',
          axisLabel: {
            formatter: '{value}',
            color: '#eee'
          },
          axisLine: {
            lineStyle: {
              color: 'rgb(147, 51, 234)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(200, 200, 200, 0.1)'
            }
          },
          nameTextStyle: {
            color: '#eee'
          }
        },
        {
          type: 'value',
          name: '错误次数',
          position: 'right',
          axisLabel: {
            formatter: '{value}',
            color: '#eee'
          },
          axisLine: {
            lineStyle: {
              color: 'rgb(239, 68, 68)'
            }
          },
          splitLine: {
            show: false
          },
          nameTextStyle: {
            color: '#eee'
          },
          min: 0,
          interval: 1
        }
      ],
      series: [
        {
          name: 'WPM',
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 3,
            color: 'rgb(147, 51, 234)' // 紫色
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(147, 51, 234, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(147, 51, 234, 0)'
              }
            ])
          },
          emphasis: {
            focus: 'series'
          },
          data: aggregatedWpm
        },
        {
          name: '错误次数',
          type: 'bar',
          yAxisIndex: 1,
          barWidth: '40%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(239, 68, 68, 0.9)'
              },
              {
                offset: 1,
                color: 'rgba(239, 68, 68, 0.5)'
              }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(255, 128, 128, 1)'
                },
                {
                  offset: 1,
                  color: 'rgba(239, 68, 68, 0.7)'
                }
              ])
            }
          },
          data: aggregatedErrors
        }
      ]
    }
  }

  // 初始化图表
  const initChart = () => {
    if (!chartContainer.value) return

    // 销毁之前的图表实例（如果存在）
    if (chart) {
      chart.dispose()
    }

    // 初始化图表
    chart = echarts.init(chartContainer.value)

    // 设置图表选项
    chart.setOption(getChartOptions())

    // 设置响应式
    window.addEventListener('resize', () => {
      chart?.resize()
    })
  }

  // 监听数据变化，更新图表
  watch(
    () => typingStore.isCompleted,
    (isCompleted) => {
      if (isCompleted) {
        // 延迟初始化图表，确保DOM已更新
        setTimeout(() => {
          initChart()
        }, 100)
      }
    }
  )

  // 在组件卸载时销毁图表实例
  onUnmounted(() => {
    if (chart) {
      chart.dispose()
    }
    window.removeEventListener('resize', () => {
      chart?.resize()
    })
  })

  onMounted(() => {
    if (typingStore.isCompleted) {
      initChart()
    }
  })
</script>
